package org.example.socketdemos.filecopy;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

@Slf4j
public class FileServerSocket {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket();
            serverSocket.bind(new InetSocketAddress(8080));

            log.info("8080端口开始监听....");
            Socket socket = serverSocket.accept();
            if (socket != null) {
                log.info("收到一个客户端连接");
                InputStream inputStream = socket.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(inputStream);

                File targetFile = new File("d:/socket2.txt");
                if (!targetFile.exists()) {
                    targetFile.createNewFile();
                }
                FileOutputStream fous = new FileOutputStream(targetFile);
                byte[] contents = new byte[4096];
                int length = -1;
                while ((length = bis.read(contents)) != -1) {
                    fous.write(contents, 0, length);
                    fous.flush();
                }

                BufferedOutputStream bous = new BufferedOutputStream(socket.getOutputStream());
                bous.write("文件传输完成\n".getBytes(StandardCharsets.UTF_8));
                bous.flush();

                Thread.sleep(Integer.MAX_VALUE);
//                socket.close();
            }
        } catch (IOException | InterruptedException e) {
            log.error(e.getMessage());
        }
    }
}
